#include "common.hpp"
#include "log.hpp"

int main(){
    //1.生成共享内存的键值
    key_t shmkey = ftok(PATH_NAME, PROJ_ID);
    if(shmkey == -1)
    {
        perror("ftok");
        exit(errno);
    }
    PrintLog("create shmkey success!", DEBUG);
    printf("shmkey: %#x\n", shmkey);
    
    //2.获取共享内存标识符
    int shmid = shmget(shmkey, SHM_SIZE, IPC_CREAT);
    if(shmid == -1)
    {
        perror("shmget");
        exit(errno);
    }
    PrintLog("get shmid success!", DEBUG);
    printf("shmid: %d\n", shmid);

    //3.建立与共享内存区域的映射
    char* shmaddr = (char*)shmat(shmid, nullptr, 0);
    if(shmaddr == (char*)-1)
    {
        perror("shmat");
        exit(errno);
    }
    PrintLog("attach share memory success!", DEBUG);
    printf("shmaddr: %p\n", shmaddr);

    //4.进程间通信
    // sleep(10);
    int fd = Openfifo(FIFO_PATH, O_WRONLY);
    while(true)
    {

       ssize_t sz = read(0, shmaddr, SHM_SIZE-1);
       if(sz > 0)
       {
            shmaddr[sz-1] = 0;
       }
       Signal(fd);
       if(strcmp(shmaddr, "quit") == 0)
       {
            break;
       }
    }
    Closefifo(fd);

    //5.解除映射
    int ret = shmdt(shmaddr);
    if(ret == -1)
    {
        perror("shmdt");
        exit(errno);
    }
    PrintLog("detach share memory success!", DEBUG);

    return 0;
}